# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from executor import submit_task
from db_config import check_user_exists
from logger_config import logger
import config

app = FastAPI(title="FASTAPI Shell Executor (optimized)")

class ShellRequest(BaseModel):
    user_id: str
    usap_id: str
    shell_content: str

@app.post("/run-shell")
def run_shell_endpoint(req: ShellRequest):
    """
    接收 shell 请求：
    1) 验证 user_id 与 usap_id 在数据库中是否存在
    2) 提交脚本到线程池执行（同步等待完成）
    3) 返回完整结果（含 request_id / stdout / stderr / success）
    """
    logger.info(f"[API] received request user={req.user_id} usap_id={req.usap_id}")

    # 1) 验证用户
    try:
        exists = check_user_exists(req.user_id, req.usap_id)
    except Exception as e:
        logger.exception(f"[API] DB error when validating user {req.user_id} {req.usap_id}: {e}")
        raise HTTPException(status_code=500, detail="database error")

    if not exists:
        logger.warning(f"[API] validation failed for user={req.user_id} usap_id={req.usap_id}")
        raise HTTPException(status_code=403, detail="user or usap_id validation failed")

    # 2) 提交任务
    future = submit_task(req.user_id, req.usap_id, req.shell_content)

    # 等待任务完成（同步接口）
    try:
        result = future.result()   # 阻塞直到 execute_task 返回
    except Exception as e:
        logger.exception(f"[API] execution future raised exception: {e}")
        raise HTTPException(status_code=500, detail="execution error")

    # 3) 返回结构化结果（HTTP 200 即表示请求已执行并返回结果结构）
    return result

@app.get("/health")
def health():
    return {"status": "ok", "max_workers": config.MAX_WORKERS}
